package org.smart4j.plugin.security;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.plugin.security.exception.AuthcException;

/**
 * description: 安全助手类
 * @version v1.0
 * @author w
 * @date 2018年11月18日下午8:38:11
 **/
public class SecurityHelper {
	
	private static final Logger logger = LoggerFactory.getLogger(SecurityHelper.class);

	/**
	 * description: 登录 
	 * @param username
	 * @param password
	 * @throws AuthcException
	 * @return void
	 * @version v1.0
	 * @author w
	 * @date 2018年11月18日 下午8:43:08
	 */
	public static void login(String username, String password) throws AuthcException{
		Subject currentUser = SecurityUtils.getSubject();
		if(null != currentUser){
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			try {
				currentUser.login(token);
			} catch (AuthenticationException e) {
				logger.error("login failure " , e);
				throw new AuthcException(e);
			}
			
		}
	}
	
	/**
	 * description: 注销
	 * @return void
	 * @version v1.0
	 * @author w
	 * @date 2018年11月18日 下午8:47:44
	 */
	public static void logout(){
		Subject currentUser = SecurityUtils.getSubject();
		if(null != currentUser){
			currentUser.logout();
		}
	}
	
	
}
